package com.jiliang.jiliangserver.service.impl;


import com.jiliang.jiliangserver.domain.MeterQuery;
import com.jiliang.jiliangserver.domain.SysUser;
import com.jiliang.jiliangserver.domain.UserMeterDto;
import com.jiliang.jiliangserver.enums.Constants;
import com.jiliang.jiliangserver.enums.UserConstants;
import com.jiliang.jiliangserver.mapper.MeterMapper;
import com.jiliang.jiliangserver.mapper.SysUserMapper;
import com.jiliang.jiliangserver.model.RegisterBody;
import com.jiliang.jiliangserver.service.ISysUserService;
import com.jiliang.jiliangserver.utils.SecurityUtils;
import com.jiliang.jiliangserver.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 * 
 * @author corner
 */
@Service
public class SysUserServiceImpl implements ISysUserService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private MeterMapper meterMapper;



    @Autowired
    protected Validator validator;

    /**
     * 根据条件分页查询用户列表
     * 
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUserList(SysUser user)
    {
        return userMapper.selectUserList(user);
    }


    /**
     * 通过用户ID查询用户
     * 
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId)
    {
        return userMapper.selectUserById(userId);
    }


    /**
     * 校验用户名称是否唯一
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public String checkUsernameUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUsernameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }




    /**
     * 新增保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user)
    {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        /*// 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);*/
        return rows;
    }

    /**
     * 注册用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user)
    {
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return userMapper.insertUser(user) > 0;
    }


    /**
     * 修改保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user)
    {
        return userMapper.updateUser(user);
    }




    /**
     * 重置用户密码
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     * 
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String username, String password)
    {
        return userMapper.resetUserPwd(username, password);
    }

    @Override
    public int deleteUserById(Long userId) {
        return userMapper.deleteUserById(userId);
    }


    /**
     * 注册
     */
    @Override
    public String register(RegisterBody registerBody)
    {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);

        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (UserConstants.NOT_UNIQUE.equals(checkUsernameUnique(sysUser)))
        {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        }
        else
        {
            //sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            boolean regFlag = registerUser(sysUser);
            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
//            else
//            {
//                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
//            }
        }
        return msg;
    }

    @Override
    public int bindMeter(SysUser user) {
        Long userId = user.getUserId();
        //删除原有绑定水表
        userMapper.deleteUserMeter(userId);

        //添加新水表
        List<Map> umlist = new ArrayList<>();
        String miidlist = user.getMiidlist();
        String[] split = miidlist.split(",");
        for (int i = 0; i < split.length; i++){
            System.out.println(split[i]);
            HashMap um = new HashMap<>();
            um.put("uid",userId);
            um.put("miid",split[i]);
            umlist.add(um);
        }
        userMapper.insertUserMeter(umlist);
        return userMapper.updateUser(user);
    }

    @Override
    public List<Map> selectUserMeterInfo(UserMeterDto query) {

        List<Map> maps = new ArrayList<>();
        //获取查询年月
        String mrmonth = query.getMrmonth();
        if(StringUtils.isNotBlank(mrmonth)){
            String[] yearMonth = mrmonth.split("\\.");
            Integer year = Integer.valueOf(yearMonth[0]);
            Integer mouth = Integer.valueOf(yearMonth[1]);
            Calendar now = Calendar.getInstance();
            // 当前年月
            int curYear = now.get(Calendar.YEAR);
            int curMonth = now.get(Calendar.MONTH) + 1;
            System.out.println(curYear);
            System.out.println(curMonth);

            //不是本月
            if(year!=curYear || mouth!=curMonth){
                query.setIsHis("1");
            }
        }

        maps = meterMapper.selectUserMeterInfo(query);

        return maps;

    }





}
